<script setup name="listinform">
import { ref, reactive, onMounted, onBeforeMount, onBeforeUnmount, watch, shallowRef } from "vue";
import OAMain from "@/components/OAMain.vue";
import OADialog from "@/components/OADialog.vue";
import OAPagination from "@/components/OAPagination.vue";
import timeFormatter from "@/utils/timeFormatter";
import informHttp from "@/api/informHttp";
import { useAuthStore } from "@/stores/auth";
import { ElMessage } from "element-plus";
import { useRouter, useRoute } from "vue-router";
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import staffHttp from "@/api/stafffHttp"


const router = useRouter();

const navigateToDetail = (id) => {
    router.push({ name: 'inform_detail', params: { pk: id } });
};

const getUrl = (id) => {
    // 这里可以返回一个默认的 URL，但实际上不会用到，因为我们使用编程式导航
    return 'javascript:void(0);';
};

const authStore = useAuthStore()

let informs = ref([])

let pagination = reactive({
    page: 1,
    total: 0
})

let dialogVisible = ref(false)
let handleIndex = 0


//------------------------------------

const route = useRoute()

const loading = ref(false)

let formRef = ref()
let formLabelWidth = '70px'

let rules = reactive({
    title: [{ required: true, message: "请输入标题！", trigger: "blur" }],
    content: [
        { required: true, message: "请输入通知内容！", trigger: "blur" },
    ],
    department_ids: [
        { required: true, message: "请选择部门！", trigger: "change" },
    ],
});

let departments = ref([])

let informForm = reactive({
    title: "",
    content: "",
    department_ids: []
})


let dialogEdisVisible = ref(false)

const onShowEditDialog = (id, title, departmentObjs, content) => {
    dialogEdisVisible.value = true
    informForm.id = id
    informForm.title = title
    informForm.department_ids = departmentObjs.map(item => item.id.toString())

    if (informForm.department_ids.length == 0){
        informForm.department_ids.unshift(0)   
    }
    console.log(departments);
    console.log(informForm.department_ids.length)
    
    informForm.content = content

}


const onSubmit = (pk) => {
    formRef.value.validate(async (valid, fields) => {
        if (valid) {
            console.log(informForm);
            try {
                loading.value = true
                let data = await informHttp.putInform(pk, informForm)
                ElMessage.success("修改成功!")
                dialogEdisVisible.value = false
                requestInformList(pagination.page)
                loading.value = false
            } catch (detail) {
                ElMessage.error(detail)
            }
        }
    })

}

// 编辑器配置-------------------

const editorRef = shallowRef()

const toolbarConfig = {}
const editorConfig = {
    placeholder: '请输入内容...',
    MENU_CONF: {
        uploadImage: {
            server: import.meta.env.VITE_BASE_URL + '/image/upload/',
            fieldName: 'image',
            maxFileSize: 2 * 1024 * 1024,
            maxNumberOfFiles: 10,
            allowedFileTypes: ['image/*'],
            headers: {
                Authorization: "JWT " + authStore.token
            },
            timeout: 6 * 1000,
            // 自定义插入图片
            customInsert(res, insertFn) {
                if (res.errno == 0) {
                    // res 服务端返回的数据
                    let data = res.data
                    let url = import.meta.env.VITE_BASE_URL + data.url
                    let href = import.meta.env.VITE_BASE_URL + data.href
                    let alt = data.alt
                    insertFn(url, alt, href)
                } else {
                    ElMessage.error(res.message)
                }
            },
            // 单文件上传失败
            onFailed(file, res) {
                console.log(`${file.name} 上传失败`, res)
            },
            // 上传错误 或 超时
            onError(file, err, res) {
                if (file.size > 0.5 * 1024 * 1024) {
                    ElMessage.error('图片文件最大不能超过0.5MB！')
                } else {
                    ElMessage.error('图片格式不正确！')
                }
            },
        }

    }
}

let mode = "default"
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
    const editor = editorRef.value
    if (editor == null) return
    editor.destroy()
})

const handleCreated = (editor) => {
    editorRef.value = editor // 记录 editor 实例，重要！
}



// 编辑器配置--------------------------




//------------------------------------


watch(
    () => pagination.page,
    (value) => {
        requestInformList(value);
    }
);

const requestInformList = async (page) => {
    try {
        let data = await informHttp.getInformList(page);
        pagination.total = data.count;
        informs.value = data.results;
    } catch (detail) {
        ElMessage.error(detail);
    }
};


const onShowDialog = (index) => {
    handleIndex = index
    dialogVisible.value = true;
}


const onDeleteInform = async () => {
    try {
        let inform = informs.value[handleIndex]
        await informHttp.deleteInform(inform.id)
        informs.value.splice(handleIndex, 1)
        dialogVisible.value = false;
        ElMessage.success("通知删除成功！")
    } catch (detail) {
        ElMessage.error(detail)
    }
}



onMounted(async () => {
    requestInformList(1)
    try {
        let data = await staffHttp.getAllDepartment()
        departments.value = data.results
    } catch (detail) {
        ElMessage.error(detail)
    }
})


</script>

<template>
    <el-dialog v-model="dialogEdisVisible" title="修改通知" :width="900">
        <el-form :model="informForm" :rules="rules" ref="formRef">
            <el-form-item label="编号" :label-width="formLabelWidth">
                <el-input disabled v-model="informForm.id" autocomplete="off" />
            </el-form-item>
            <el-form-item label="标题" :label-width="formLabelWidth">
                <el-input v-model="informForm.title" autocomplete="off" />
            </el-form-item>
            <el-form-item label="部门" :label-width="formLabelWidth">
                <el-select multiple v-model="informForm.department_ids" placeholder="请选择部门">
                    <el-option :value="0" label="全部部门"></el-option>
                    <el-option v-for="item in departments" :label="item.name" :value="item.id.toString()" :key="item.id" />
                </el-select>
            </el-form-item>
            <el-form-item label="内容" :label-width="formLabelWidth">
                <div style="border: 1px solid #ccc; width: 100%;">
                    <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig"
                        :mode="mode" />
                    <Editor style="height: 500px; overflow-y: hidden;" v-model="informForm.content"
                        :defaultConfig="editorConfig" :mode="mode" @onCreated="handleCreated" />
                </div>
            </el-form-item>
            <el-form-item>
                <div style="text-align: right; flex: 1;">
                    <el-button type="primary" @click="onSubmit(informForm.id)">提交</el-button>
                </div>
            </el-form-item>
        </el-form>

    </el-dialog>

    <OADialog v-model="dialogVisible" title="提示" @submit="onDeleteInform">
        <span>你确定要删除这条通知吗?</span>
    </OADialog>
    <OAMain title="通知列表">
        <el-card>
            <el-table v-loading="loading" :data="informs" >
                <el-table-column label="标题">
                    <template #default="scope">
                        <el-badge v-if="scope.row.reads.length == 0" value="new" class="item">
                            <el-link :href="getUrl(scope.row.id)" @click.prevent="navigateToDetail(scope.row.id)"
                                class="custom-router-link">
                                <strong>{{ scope.row.title }}</strong>
                            </el-link>
                        </el-badge>
                        <el-link v-else :href="getUrl(scope.row.id)" @click.prevent="navigateToDetail(scope.row.id)"
                            class="custom-router-link">
                            <strong>{{ scope.row.title }}</strong>
                        </el-link>
                    </template>
                </el-table-column>
                <el-table-column label="发布者">
                    <template #default="scope">
                        {{
                            "[" +
                            scope.row.author.department.name +
                            "]" +
                            scope.row.author.realname
                        }}
                    </template>
                </el-table-column>

                <el-table-column label="发布时间">
                    <template #default="scope">
                        {{ timeFormatter.stringFromDateTime(scope.row.create_time) }}
                    </template>
                </el-table-column>

                <el-table-column label="部门可见">
                    <template #default="scope">
                        <el-tag v-if="scope.row.publish" type="success">全部部门</el-tag>
                        <el-tag v-else v-for="department in scope.row.departments" :key="department.name" type="info">
                            {{ department.name }} </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template #default="scope">
                        <el-button plain v-if="scope.row.author.uid == authStore.user.uid"
                            @click="onShowDialog(scope.$index)" type="danger" icon="Delete" />
                        <el-button v-else disabled type="default">无</el-button>

                        <el-button plain v-if="scope.row.author.uid == authStore.user.uid"
                            @click="onShowEditDialog(scope.row.id, scope.row.title, scope.row.departments, scope.row.content)"
                            type="primary" icon="Edit" />
                        <el-button v-else disabled type="default">无</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <template #footer>
                <OAPagination v-model="pagination.page" :total="pagination.total"></OAPagination>
            </template>
        </el-card>
    </OAMain>
</template>

<style scoped>
.el-badge {
    margin-right: 4px;
    margin-top: 4px;
}

.el-tag {
    margin-right: 4px;

}

.custom-router-link {
    color: #409EFF;
    /* 链接颜色 */
    text-decoration: none;
    /* 去除下划线 */
    margin-right: 10px;
    /* 右边距 */
}

.item {
    margin-top: 10px;
    margin-right: 10px;
}

.example-showcase .el-loading-mask {
  z-index: 9;
}
</style>
